// @ts-nocheck
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
} from "react-native";
import { Picker } from "@react-native-picker/picker";
import { useEffect, useState } from "react";
import { manager } from "utils/bleManage";
import { useAppSelector } from "app/store";
import toast from "utils/toast";
import {
  WritableWithResponse,
  determineCurrentDevice,
  getStorageData,
  setStorageData,
} from "utils";
import iconv from "@vscode/iconv-lite-umd";
import translate from "utils/translate";
const Buffer = require("@craftzdog/react-native-buffer").Buffer;
function gbkHexToString(hexString: string) {
  // 将十六进制字符串转换为 Buffer
  const buffer = Buffer.from(hexString, "hex");
  // 将 Buffer 转换为字符串
  const result = iconv.decode(buffer, "gbk");
  return result;
}
export default ({ navigation }: RootStackScreenProps) => {
  const connectedDevice = useAppSelector((state) => {
    return state.app.connectedDevice;
  });
  const [form, setForm] = useState({
    range: "",
    point: "",
    communication: "",
    unit: "",
    scale: "",
    weight: "",
    zeroTracking: "",
  });
  useEffect(() => {
    getStorageData("settings").then((value) => {
      if (value) {
        const data = JSON.parse(value);
        setForm((pre) => {
          return {
            ...pre,
            ...data,
          };
        });
      } else {
        getData();
      }
    });
  }, []);
  const getData = async () => {
    const services = await manager
      .discoverAllServicesAndCharacteristicsForDevice(connectedDevice as string)
      .then((device) => {
        return device.services();
      })
      .catch(() => {
        toast(translate("main.error"));
      });
    if (services) {
      const item = determineCurrentDevice(services);
      if (item) {
        const characteristicsList = await item.characteristics();
        for (let current of characteristicsList) {
          if (current.isWritableWithResponse && current.isNotifiable) {
            try {
              const resData = await WritableWithResponse(
                current,
                "3C9500003E09"
              );
              const keyList = [
                "point",
                "scale",
                "unit",
                "communication",
                "zeroTracking",
              ];
              const List = [];
              const formatData = resData
                .replaceAll(/\s/g, "")
                .slice(4)
                .slice(0, -4)
                .match(/.{1,2}/g);
              for (let p = 0; p < formatData.length; p++) {
                if (p >= 2) {
                  List.push([
                    keyList[p - 2],
                    parseInt(formatData[p], 16).toString(),
                  ]);
                }
              }
              List.unshift([
                "range",
                parseInt(formatData[0] + formatData[1], 16).toString(),
              ]);
              const obj = Object.fromEntries(List);
              setForm((pre) => {
                return {
                  ...pre,
                  ...obj,
                };
              });
              setStorageData("settings", JSON.stringify(obj));
              toast(translate("main.success"));
            } catch {
              toast(translate("main.error"));
            }
            return;
          }
        }
      } else {
        toast(translate("main.error"));
      }
    }
  };
  const numberTohex = (string) => {
    const buffer = new ArrayBuffer(2);
    const view = new DataView(buffer);
    // 使用 little-endian（小端序）存储数字
    view.setUint16(0, string, false);

    const hexString = Array.from(new Uint8Array(buffer), (byte) =>
      byte.toString(16).padStart(2, "0")
    ).join("");
    return hexString;
  };
  const onSync = async (prop: keyof typeof form) => {
    if (!form[prop]) return toast(translate("main.labelError"));
    const obj: typeof form = {
      range: "89",
      weight: "88",
      scale: "8A00",
      communication: "8B00",
      unit: "8C00",
      point: "8D00",
      zeroTracking: "8E00",
    };
    const services = await manager
      .discoverAllServicesAndCharacteristicsForDevice(connectedDevice as string)
      .then((device) => {
        return device.services();
      })
      .catch(() => {
        toast(translate("main.error"));
      });
    if (services) {
      const item = determineCurrentDevice(services);
      if (item) {
        const characteristicsList = await item.characteristics();
        for (let current of characteristicsList) {
          if (current.isWritableWithResponse && current.isNotifiable) {
            let formatValue = "";
            if (["range", "weight"].includes(prop)) {
              const regex = /.{2}/g;
              formatValue = numberTohex(form[prop]).match(regex).join("") ?? "";
            } else {
              formatValue = Buffer.from([form[prop]]).toString("hex");
            }
            try {
              await WritableWithResponse(
                current,
                `3C${obj[prop] + formatValue}3E09`
              );
              getStorageData("settings").then((value) => {
                if (value) {
                  const data = JSON.parse(value);
                  setStorageData(
                    "settings",
                    JSON.stringify(
                      Object.assign(data, {
                        prop: form[prop],
                      })
                    )
                  ).then(() => {
                    toast(translate("main.success"));
                  });
                }
              });
            } catch {
              toast(translate("main.error"));
            }
            return;
          }
        }
      } else {
        toast(translate("main.error"));
      }
    }
  };
  const List = [
    // {
    //   label: "砝码值",
    //   placeholder: "请输入砝码值",
    //   unit: "kg",
    //   keyboardType: "numeric",
    //   prop: "weight",
    // },
    {
      label: translate("main.range"),
      placeholder: translate("main.labelError"),
      unit: "kg",
      keyboardType: "numeric",
      prop: "range",
    },
    {
      label: translate("main.DivisionValue"),
      unit: "g",
      prop: "scale",
      component: Picker,
      componentProps: {
        options: [
          {
            label: "1",
            value: "1",
          },
          {
            label: "2",
            value: "2",
          },
          {
            label: "5",
            value: "3",
          },
          {
            label: "10",
            value: "4",
          },
          {
            label: "20",
            value: "5",
          },
          {
            label: "50",
            value: "6",
          },
        ],
      },
    },
    {
      label: translate("main.CommunicationMode"),
      placeholder: translate("main.labelError"),
      prop: "communication",
      component: Picker,
      componentProps: {
        options: [
          {
            label: "Stb1",
            value: "1",
          },
          {
            label: "Ser2",
            value: "2",
          },
          {
            label: "Ser3",
            value: "3",
          },
          {
            label: "Ser4",
            value: "4",
          },
          {
            label: "Ser5",
            value: "5",
          },
          {
            label: "Ser6",
            value: "6",
          },
          {
            label: "Ser7",
            value: "7",
          },
        ],
      },
      unit: "kg",
    },
    // {
    //   label: "重量单位",
    //   placeholder: "请选择重量单位",
    //   component: Picker,
    //   componentProps: {
    //     options: [
    //       {
    //         label: "公斤",
    //         value: "0",
    //       },
    //       {
    //         label: "市斤",
    //         value: "1",
    //       },
    //     ],
    //   },
    //   unit: "kg",
    //   prop: "unit",
    // },
    {
      label: translate("main.WeightDecimalPoint"),
      placeholder: translate("main.labelError"),
      prop: "point",
      component: Picker,
      componentProps: {
        options: [
          {
            label: "0",
            value: "0",
          },
          {
            label: "1",
            value: "1",
          },
          {
            label: "2",
            value: "2",
          },
          {
            label: "3",
            value: "3",
          },
        ],
      },
      unit: "kg",
    },
    // {
    //   label: "零点跟踪",
    //   placeholder: "请输入1~90之间的数字",
    //   unit: "d",
    //   keyboardType: "numeric",
    //   prop: "zeroTracking",
    // },
  ];
  return (
    <ScrollView
      style={{
        flex: 1,
        backgroundColor: "#fff",
      }}
      contentContainerStyle={{
        alignItems: "center",
      }}
    >
      {List.map((item) => {
        return (
          <View
            key={item.label}
            style={{
              flexDirection: "row",
              alignItems: "center",
              paddingVertical: item.component ? 5 : 16,
              borderBottomColor: "#eeeeee",
              justifyContent: "space-between",
              borderBottomWidth: 1,
              width: 343,
            }}
          >
            <Text
              style={{
                width: 64,
              }}
            >
              {item.label}
            </Text>
            {item.component ? (
              <Picker
                style={{ flex: 1 }}
                selectedValue={form[item.prop]}
                onValueChange={(value) => {
                  setForm((pre) => {
                    return {
                      ...pre,
                      [item.prop]: value,
                    };
                  });
                }}
              >
                <Picker.Item
                  label={translate("main.PleaseSelect")}
                  value=""
                ></Picker.Item>
                {item.componentProps.options.map((current) => {
                  return (
                    <Picker.Item
                      label={current.label}
                      value={current.value}
                    ></Picker.Item>
                  );
                })}
              </Picker>
            ) : (
              <TextInput
                style={{
                  flex: 1,
                  paddingHorizontal: 24,
                }}
                // @ts-ignore
                keyboardType={item.keyboardType}
                placeholder={item.placeholder}
                onChangeText={(value) => {
                  setForm((pre) => {
                    return {
                      ...pre,
                      [item.prop]: value,
                    };
                  });
                }}
                value={form[item.prop]}
              ></TextInput>
            )}

            <View
              style={{
                flexDirection: "row",
                alignItems: "center",
              }}
            >
              {!item.component && <Text>{item.unit}</Text>}
              <TouchableOpacity
                style={{
                  paddingHorizontal: 8,
                  paddingVertical: 4,
                  backgroundColor: "#0181fe1a",
                  alignItems: "center",
                  justifyContent: "center",
                  borderRadius: 2,
                  borderWidth: 1,
                  borderColor: "#0181FE",
                  marginLeft: item.component ? 0 : 16,
                }}
                onPress={() => {
                  onSync(item.prop as keyof typeof form);
                }}
              >
                <Text
                  style={{
                    color: "#0181FE",
                  }}
                >
                  {translate("scale.settings")}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        );
      })}
      <View
        style={{
          flexDirection: "row",
          backgroundColor: "#fff",
          bottom: 0,
          width: 343,
          //   paddingVertical: 12,
          marginTop: 40,
          justifyContent: "center",
        }}
      >
        <TouchableOpacity
          style={{
            ...styles.button,
            backgroundColor: "#0181FE",
            borderColor: "#0181FE",
            borderTopRightRadius: 0,
            borderBottomRightRadius: 0,
          }}
          onPress={getData}
        >
          <Text
            style={{
              color: "#FFFFFF",
            }}
          >
            {translate("main.argument")}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{
            ...styles.button,
            backgroundColor: "rgba(1, 129, 254, 0.1)",
            borderColor: "#0181FE",
            borderTopLeftRadius: 0,
            borderBottomLeftRadius: 0,
          }}
          onPress={() => {
            navigation.goBack();
          }}
        >
          <Text
            style={{
              color: "#0181FE",
            }}
          >
            {translate("main.Back")}
          </Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
};
const styles = StyleSheet.create({
  button: {
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 45,
    paddingVertical: 12,
    borderWidth: 1,
    borderRadius: 4,
    flex: 1,
  },
});
